import axios from 'axios'
import { ElMessage } from 'element-plus' // 导入 ElMessage
import { useUserStore } from '../stores/user.js'

// create an axios instance
export const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  // baseURL: '/api',
  timeout: 5000,
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    if (userStore.token != null) {
      config.headers['X-Token'] = userStore.token
    }
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  },
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.errno !== 0) {
      ElMessage({
        message: res.errmsg || '请求失败', // 建议使用中文提示
        type: 'error',
        duration: 5000,
      })
      return Promise.reject(new Error(res.errmsg || 'Error'))
    } else {
      return res
    }
  },
  (error) => {
    console.log('err' + error)
    ElMessage({
      message: error.message || '网络错误，请稍后再试', // 优化错误提示
      type: 'error',
      duration: 5000,
    })
    return Promise.reject(error)
  },
)
